package com.likan.chqjtgc.service.impl;

import com.likan.chqjtgc.commons.PageVo;
import com.likan.chqjtgc.entity.BasicUser;
import com.likan.chqjtgc.mapper.BasicUserMapper;
import com.likan.chqjtgc.service.BasicUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户基本信息表 服务实现类
 * </p>
 *
 * @author lxh
 * @since 2021-01-10
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class BasicUserServiceImpl extends ServiceImpl<BasicUserMapper, BasicUser> implements BasicUserService {

    @Autowired
    private BasicUserMapper baseMapper;
    @Value("${defaultPassword}")
    private String defaultPassword;

    @Override
    public IPage<BasicUser> findListByPage(PageVo< BasicUser> page){
           Page<BasicUser> pageInfo = new Page<>(page.getCurrent(), page.getSize());
       QueryWrapper<BasicUser> wrapper = new QueryWrapper<>();
        //todo:构造查询参数 根据业务添加

       if (StringUtils.isNotBlank(page.getSortField())){
           wrapper.orderBy(true,0!=page.getDirection() ,page.getSortField());
       }else {
           wrapper.orderByDesc("id");
       }
        IPage<BasicUser> iPage = baseMapper.selectPage(pageInfo, wrapper);
        return iPage;
    }

    @Override
    public Boolean add(BasicUser basicUser){
        if (StringUtils.isBlank(basicUser.getPassword())){
            basicUser.setPassword(new BCryptPasswordEncoder().encode(defaultPassword));
        }else {
            basicUser.setPassword(new BCryptPasswordEncoder().encode(basicUser.getPassword()));
        }
        baseMapper.insert(basicUser);
        return true;
    }

    @Override
    public Boolean delete(Long id){
        baseMapper.deleteById(id);
        return true;
    }

    @Override
    public Boolean updateData(BasicUser basicUser){
        baseMapper.updateById(basicUser);
        return true;
    }

    @Override
    public BasicUser findById(Long id){
        BasicUser basicUser = baseMapper.selectById(id);
        return basicUser;
    }
}
